package com.itheima.service.Impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.common.PageBean;
import com.itheima.dto.ClazzDto;
import com.itheima.dto.ClazzQueryDto;
import com.itheima.mapper.ClazzMapper;
import com.itheima.mapper.StudentMapper;
import com.itheima.pojo.Clazz;
import com.itheima.service.ClazzService;
import com.itheima.vo.ClazzVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;

@Service
public class ClazzServiceImpl implements ClazzService {

    @Autowired
    ClazzMapper clazzMapper;

    @Autowired
    StudentMapper studentMapper;

    @Override
    public PageBean ClazzQuery(ClazzQueryDto dto) {


        PageHelper.startPage(dto.getPage(), dto.getPageSize());
        Page<ClazzVo> page = clazzMapper.ClazzQuery(dto);
        page.forEach(clazzVo -> {
            if (LocalDate.now().isAfter(clazzVo.getBeginDate()) && LocalDate.now().isBefore(clazzVo.getEndDate())) {
                clazzVo.setStatus("开班中");
            } else {
                clazzVo.setStatus("未开班");
            }
        });
        Long total = page.getTotal();
        List<ClazzVo> rows = page.getResult();
        return new PageBean(total, rows);
    }

    @Override
    public void insert(ClazzDto clazz) {

        clazz.setCreateTime(LocalDateTime.now());
        clazz.setUpdateTime(LocalDateTime.now());

        clazzMapper.insert(clazz);
    }

    @Override
    public List<Clazz> Queryall() {
        return clazzMapper.Queryall();
    }

    @Override
    public void delete(Integer id) {


        Integer count = studentMapper.countByClazzId(id);
        if (count > 0)
            throw new RuntimeException("该班级下有学生，不能删除");
        clazzMapper.delete(id);
    }

    @Override
    public Clazz getById(Integer id) {
        return clazzMapper.getById(id);
    }

    @Override
    public void update(ClazzDto clazz) {
        clazz.setUpdateTime(LocalDateTime.now());
        clazzMapper.update(clazz);
    }

}
